package com.core.zyyz.redis.temp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class InitializerCache {
    RedissonClient redissonClient;

    public InitializerCache(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public <T> List<T> getList(String key, Class<T> clazz) {
        String jsonStr = this.getString(key);
        return JSON.parseArray(jsonStr, clazz);
    }

    public <T> void setList(String key, List<T> value) {
        this.setObject(key, value);
    }

    public <K, V> void setMap(String key, Map<K, V> map) {
        this.setObject(key, map);
    }

    public <K, V> void setMap(String key, Map<K, V> tMap, long timestamp) {
        this.setObject(key, tMap, timestamp);
    }

    public void setObject(String key, Object value) {
        this.setObject(key, value, -1L);
    }

    private void setObject(String key, Object value, long timestamp) {
        if (!StringUtils.isBlank(key) && null != value) {
            RBucket<Object> rBucket = this.redissonClient.getBucket(key);
            rBucket.set(JSON.toJSONString(value));
            if (-1L != timestamp) {
                rBucket.expireAt(timestamp);
            }

        }
    }

    public <T> T getObject(String key, Class<T> clazz) {
        String jsonStr = this.getString(key);
        return JSON.parseObject(jsonStr, clazz);
    }

    public String getString(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        } else {
            Object obj = this.redissonClient.getBucket(key).get();
            return obj == null ? null : obj.toString();
        }
    }

    public <K, V> Map<K, V> getMap(String key, TypeReference<Map<K, V>> typeReference) {
        String jsonStr = this.getString(key);
        return (Map)JSON.parseObject(jsonStr, typeReference, new Feature[0]);
    }

//    public <K, V> Map<K, V> getMapFastjsonCodec(String key) {
//        RMap<K, V> pcmcSequenceMap = this.redissonClient.getMap(key, new FastjsonCodec());
//        return pcmcSequenceMap.readAllMap();
//    }

    public void setString(String key, String value, int expire, TimeUnit timeUnit) {
        RBucket<String> rBucket = this.redissonClient.getBucket(key);
        rBucket.set(value, (long)expire, timeUnit);
    }
}

